package com.bdqn.base.jedis;

import com.mysql.cj.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

/**
 * Redis连接操作
 * 
 * @author Lilibo
 *
 */
public class RedisClient {


	private JedisPool jedisPool;

	// private ShardedJedisPool shardedJedisPool;

	private static class SingletonHolder {
		private static String host = "127.0.0.1";
		private static int port = 6379;
		private static final RedisClient instance = new RedisClient(host, port);
	}

	public static RedisClient getInstance() {
		return SingletonHolder.instance;
	}

	public RedisClient(String host, int port) {
		initialPool(host, port);
		// initialShardedPool();
		// jedisPool.getResource().flushDB();
		System.out.println("------------ Redis Server Initial (" + host + ":" + port + ") ------------");
	}

	public JedisPool jedisPool() {
		return jedisPool;
	}

	public Jedis jedis() {
		return jedisPool.getResource();
	}

	/*public ShardedJedis shardedJedis() {
		return shardedJedisPool.getResource();
	}*/

	/**
	 * 初始化非切片池
	 */
	private void initialPool(String host, int port) {
		JedisPoolConfig config = RedisConfig.getJedisPoolConfig();
		if (!StringUtils.isNullOrEmpty(RedisConfig.password)) {
			jedisPool = new JedisPool(config, host, port, Protocol.DEFAULT_TIMEOUT, RedisConfig.password);
		} else {
			jedisPool = new JedisPool(config, host, port);
		}
	}

	/**
	 * 释放非切片连接
	 */
	public void release(Jedis jedis, boolean isbroken) {
		if (jedisPool != null && jedis != null) {
			if (isbroken) {
				jedisPool.close();
			} else {
				jedisPool.close();
			}
		}
	}

	// 初始化切片池
	/*private void initialShardedPool() {
		JedisPoolConfig config = RedisConfig.getJedisPoolConfig();
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		shards.add(new JedisShardInfo("127.0.0.1", 6379, "master"));
		shardedJedisPool = new ShardedJedisPool(config, shards);
	}*/

	// 释放切片连接
	/*public void returnResource(ShardedJedis shardedJedis) {
		if (shardedJedisPool != null && shardedJedis != null) {
			shardedJedisPool.returnResource(shardedJedis);
		}
	}*/

}
